home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C21 / NString.h < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.7 KB  |  62 lines

  1. //: C21:NString.h
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // A "numbered string" that indicates which
  7. // occurrence this is of a particular word
  8. #ifndef NSTRING_H
  9. #define NSTRING_H
  10. #include <string>
  11. #include <map>
  12. #include <iostream>
  13.  
  14. class NString {
  15.   std::string s;
  16.   int occurrence;
  17.   struct Counter {
  18.     int i;
  19.     Counter() : i(0) {}
  20.     Counter& operator++(int) { 
  21.       i++;
  22.       return *this;
  23.     } // Post-incr
  24.     operator int() { return i; }
  25.   };
  26.   // Keep track of the number of occurrences:
  27.   typedef std::map<std::string, Counter> csmap;
  28.   static csmap occurMap;
  29. public:
  30.   NString() : occurrence(0) {}
  31.   NString(const std::string& x) 
  32.     : s(x), occurrence(occurMap[s]++) {}
  33.   NString(const char* x) 
  34.     : s(x), occurrence(occurMap[s]++) {}
  35.   // The synthesized operator= and 
  36.   // copy-constructor are OK here
  37.   friend std::ostream& operator<<(
  38.     std::ostream& os, const NString& ns) {
  39.     return os << ns.s << " [" 
  40.       << ns.occurrence << "]";
  41.   }
  42.   // Need this for sorting. Notice it only 
  43.   // compares strings, not occurrences:
  44.   friend bool 
  45.   operator<(const NString& l, const NString& r) {
  46.     return l.s < r.s;
  47.   }
  48.   // For sorting with greater<NString>:
  49.   friend bool 
  50.   operator>(const NString& l, const NString& r) {
  51.     return l.s > r.s;
  52.   }
  53.   // To get at the string directly:
  54.   operator const std::string&() const {return s;}
  55. };
  56.  
  57. // Allocate static member object. Done here for
  58. // brevity, but should actually be done in a 
  59. // separate cpp file:
  60. NString::csmap NString::occurMap;
  61. #endif // NSTRING_H ///:~
  62.